<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Common\CommonController;
use Illuminate\Http\Request;
use App\Model\Common\User;
use App\Model\Common\EmailLog;
use App\Model\Common\LoginLog;
use Validator;
use Illuminate\Support\Facades\Schema;

class UserController extends CommonController
{
    public function login(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'name' => 'bail|required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->output(10005, $validator->errors());
        }

        $query_data = [];
        if (is_email($data['name'])) {
            $query_data['email'] = $data['name'];
        } else {
            $query_data['name'] = $data['name'];
        }
        // $query_data['password'] = $request->get('password');
        $User = new User();
        $user = $User->where($query_data)->first();
        if (!$user) {
            return $this->output(20002);
        }

        if (1 != $user->status) {
            return $this->output(80002); //用户已被锁定
        }

        $minutes = 60;
        $uid = $user->id;
        $error_count = cache('login_error_count:'.$uid) ?: '0|0';
        list($error_count, $last_error_time) = explode('|', $error_count);
        if ($last_error_time + 3600 * 24 < time()) {
            cache(['login_error_count:'.$uid => null], $minutes);
            session(['login_need_captcha' => null]);
            $error_count = 0;
        }
        if ($error_count >= 3 && !captcha_check($request->input('captcha'))) {
            // if ($error_count >= 3 && false) {
            if ($error_count >= 3) {
                session(['login_need_captcha' => 1]);
            }

            return $this->output(20004, '', [
                'login_need_captcha' => session('login_need_captcha') ?: 0,
            ]);
        }
        if (!$user->checkPassword($data['password'])) {
            cache(['login_error_count:'.$uid => ($error_count + 1).'|'.time()], $minutes);
            if ($error_count + 1 >= 3) {
                session(['login_need_captcha' => 1]);
            }

            return $this->output(20003, '', [
                'login_need_captcha' => session('login_need_captcha') ?: 0,
                'captcha_src' => captcha_src(),
            ]);
        } elseif ($error_count > 0) {
            cache(['login_error_count:'.$uid => null], $minutes);
            session(['login_need_captcha' => null]);
        }
        
        $re = $User->logTheUser($user);  //注册后自动登录
        // session(['user:uid' => $user->id]);
        // session(['user:gid' => $user->group_id]);
        // session(['user:name' => $user->name]);
        $redirect = $request->input('redirect');
        if (!$redirect) {
            $redirect = route('console/root');
        }

        $Log = new LoginLog();
        $Log->ip = $request->ip();
        $Log->uid = $user->id;
        $Log->type = 1;
        $Log->save();

        return $this->output(0, '登录成功', [
            'uid' => $user->id,
            'gid' => $user->group_id,
            'name' => $user->name,
            'redirect' => $redirect,
        ]);
    }

    public function register(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'name' => 'bail|required|max:24|min:6|unique:user,name',
            'password' => 'required',
            'repassword' => 'required|same:password',
            'email' => 'bail|required|email|unique:user,email',
            'code' => 'bail|required',
        ]);

        if ($validator->fails()) {
            return $this->output(10005, $validator->errors());
        }

        // if (!$request->has('captcha')) {
        //     return $this->output(20010);
        // }
        // $a = captcha_check($request->input('captcha', ''));
        // if (!$a) {
        //     return $this->output(20011);
        // }

        $re = $this->_checkEmailCode($data['email']);
        if (true !== $re) {
            return $re;
        }

        $User = new User();

        $user = $User->add($request->only($User->registerFields));

        if (!$user) {
            return $this->output(10005, $User->getError());
        }
        $user = $User->find($user->id);

        $User->doLogout();    //先退出登陆
        $re = $User->logTheUser($user);  //注册后自动登录
        if (!$re) {
            return $this->output(10001, $User->getError());
        }

        return $this->output(0, '', array('uid' => $user->id, 'name' => $user->name, 'redirect' => route('user/login')));
    }

    public function _checkEmailCode($email, $opt = [])
    {
        $request = request();
        $code = $request->post('code', '');
        if (!$code) {
            return $this->output(10005);
        }

        $EmailLog = new EmailLog();
        if (isset($opt['type'])) {
            $log = $EmailLog->where('email', $email)->where('type', $opt['type'])->orderBy('id', 'desc')->first();
        } else {
            $log = $EmailLog->where('email', $email)->orderBy('id', 'desc')->first();
        }

        $s_time = strtotime($log['create_time']);
        if (time() - $s_time > 1800) {
            return $this->output(20007);
        }

        if ($code != $log['code']) {
            return $this->output(20008);
        }

        return true;
    }

    public function resetPassword(Request $request)
    {
    }

    public function findPassword(Request $request)
    {
    }

    public function updateProfile(Request $request)
    {
    }

    public function get(Request $request)
    {
        // $request = request();
        // $validator = Validator::make($request->all(), [
        //     'title' => 'required|unique:posts|max:255',
        //     'body' => 'required',
        // ]);
        // $errors = $validator->errors();
        // var_dump($errors);
        // $date = '2018-02-11';
        // $now = date('Y-m-d');

        // echo $now.' > '.$date;
        // echo '<br>';

        // echo strtotime($now).' > '.strtotime($date);
        // echo '<br>';
        // if (strtotime($now) > strtotime($date)) {
        //     echo 'true';
        // } else {
        //     echo 'false';
        // }

        // $num = '00000000012341234123412341123412341234123412341234324';
        // if (is_numeric($num))
        // {
        //     echo 'yes';
        // }
        // else
        // {
        //     echo 'no';
        // }

        // for ($i=0; $i < 0; $i++) { 
        //     echo 1;
        // }
        // echo 2;



        $list = Schema::getColumnListing('category_api');
        return $this->output(0,'',$list);
    }
}
